/**
* 添加银行卡
*/
import React, { Component } from 'react';
import { View, StyleSheet, Text, Image, TouchableOpacity, ScrollView, TextInput } from "react-native";
import { connect } from 'react-redux';
import { Colors, Dimens, ImageRes, getPovinceAndCityId, getPovinceAndCityName } from '../../utils/Assets';
import { create_service } from '../../redux/index.js';
import { Contract } from '../../service/index.js';
import ImagePicker from 'react-native-image-picker'
import { Actions } from 'react-native-router-flux';
import {toast} from '../../utils/Toast';
import { ProgressView } from '../custom/index';
import Picker from 'react-native-picker'


const days = []
for (let i = 1; i < 32; i++) {
  if (i < 10) {
    days.push('0' + i.toString())
  } else {
    days.push(i.toString())
  }
}

class BankCardInfoView extends Component {
    constructor(props) {
        super(props);

        this.state = {
            loading: false,
            bank_list: [],
            area_list:[],

            bank_card: this.props.info.full_card_number,

            statement_date:this.props.info.statement_date,
            repayment_date:this.props.info.repayment_date,
            valid_date:this.props.info.valid_date,
            province:0,
            city:0,
            bank_id:this.props.info.banks_id,
            mobile:this.props.info.mobile,
            quota: this.props.info.quota,
            cvn2:this.props.info.cvv2,

            area_value:'',
            bank_name:this.props.info.name,
            area: ['', ''],
            bank: [''],
            validityDate: '',
            paymentDate: [''],
            repaymentDate: [''],
            datePickerValue: new Date()
        }
        this.options = {
            title: '选择照片',
            cancelButtonTitle: '取消',
            takePhotoButtonTitle: '拍照',
            chooseFromLibraryButtonTitle: '从相册中选取',
            mediaType: 'photo',
            maxWidth: 750,
            maxHeight: 1000,
            quality: 0.5,
        }
        this.pickData = [],
        this.pickArea = [],
        this.userInfo = props.userInfo
    }
    componentDidMount() {
        this.getBankInfo()
        this.getProvinceAndCity()
        // Picker.hide()
    }

    componentWillUnmount(){
        Picker.hide()
    }

    componentWillReceiveProps(nextProps) {
        this.userInfo = nextProps.userInfo
    }
    getBankInfo() {
        this.setState({ loading: true })
        this.props.dispatch(create_service(Contract.GET_BANKS_LIST, {})).then((res) => {
            if (res) {
                for (let index = 0; index < res.length; index++) {
                    this.pickData.push(res[index].name)
                }
                this.setState({ loading: false, bank_list: res })
            } else {
                this.setState({ loading: false })
            }
        })
    }
    getProvinceAndCity() {
        this.setState({ loading: true })
        this.props.dispatch(create_service(Contract.GET_PROVINCE_CITY_LIST, {})).then((res) => {
            if (res) {
                let that = this;
                res.forEach(function (item) {
                    var object = {}
                    var citys = item.city.map(function (city) {
                        return city.name
                    })
                    if (citys.length === 0) {
                        citys = [item.name]
                    }
                    object[item.name] = citys

                    console.log(object);
                    that.pickArea.push(object)
                })

                let area = getPovinceAndCityName(res, [this.props.info.province, this.props.info.city])
                
                this.setState({ loading: false, area_list: res, area, area_value:area[0] + ' '+ area[1] })
            } else {
                this.setState({ loading: false })
            }
        })
    }

    getBankId = (sourceData, selected) => {
        let id = ''
        if (selected[0]) {
            sourceData.some(item => {
                if (item.name === selected[0]) {
                    id = item.id
                    return true
                }
            })
        }
        return id
    }

    updateClick() {
        let bankId = this.getBankId(this.state.bank_list, this.state.bank_name)
        bankId = bankId?bankId:this.props.info.banks_id;
        let areaIds = getPovinceAndCityId(this.state.area_list, this.state.area)

        if (!this.state.bank_card) {
            toast('请填写银行卡号')
            return
        }
        if (!bankId) {
            toast('请选择发卡行')
            return
        }
        if (!this.state.mobile) {
            toast('请输入信用卡预留手机号码')
            return
        }
        if (!this.state.cvn2) {
            toast('请输入信用卡背面后三位安全码')
            return
        }
        if (!this.state.quota) {
            toast('请输入信用卡额度')
            return
        }
        let params = {
            bankCardId: this.props.info.id,
            token: this.userInfo.token,
            banks_id: bankId,
            bank_card: this.state.bank_card,
            valid_date: this.state.valid_date,
            cvv2: this.state.cvn2,
            statement_date: this.state.statement_date[0],
            repayment_date: this.state.repayment_date[0],
            quota: this.state.quota,
            province: areaIds[0],
            city: areaIds[1],
            mobile: this.state.mobile,
            type: '02',
        }
        this.setState({ loading: true })
        this.props.dispatch(create_service(Contract.POST_USER_BANKCARD_UPDATE, params)).then((res) => {
            console.log(1111);
            if (res) {
                if (this.props.reloadList) {
                    this.props.reloadList()
                }
                Actions.pop()
                toast('修改成功')
            }
            this.setState({ loading: false })
        })
    }
    showImagePicker() {
        ImagePicker.showImagePicker(this.options, (response) => {
            if (response.didCancel) { } else if (response.error) { } else if (response.customButton) { } else {
                let source = { uri: Dimens.isIOS ? response.uri.replace('file://', '') : response.uri, isStatic: true }
                this.uploadImage(source.uri)
            }
        })
    }
    uploadImage(image) {
        this.setState({ loading: true })
        let filename = image.substr(image.lastIndexOf('/') + 1)
        let bank_image = { uri: image, type: 'multipart/form-data', name: filename };
        this.props.dispatch(create_service(Contract.POST_USER_OCR_BANK, { bank_image: bank_image, token: this.userInfo.token })).then((res) => {
            if (res) {
                this.setState({ bank_card: res.bank_card_number, loading: false })
            } else {
                this.setState({ loading: false })
            }
        })
    }

    //选择开户行
    handleShowBankPicker = () => {
        let payload = {
        pickerConfirmBtnColor: [55, 142, 251, 1],
        pickerCancelBtnColor: [55, 142, 251, 1],
        pickerData: this.pickData,
        selectedValue: [this.state.bank_name],
        pickerBg: [255, 255, 255, 1],
        pickerRowHeight:40,
        pickerTitleText: '选择开户行',
        pickerCancelBtnText: '取消',
        pickerConfirmBtnText: '确定',
        onPickerConfirm: data => {
            this.setState({ bank_name: data })
        }
        }
        Picker.init(payload)
        Picker.show()
    }

    //选择地区
    handleShowPickerArea = () => {
        let payload = {
          pickerConfirmBtnColor: [55, 142, 251, 1],
          pickerCancelBtnColor: [55, 142, 251, 1],
          pickerBg: [255, 255, 255, 1],
          pickerData: this.pickArea,
          selectedValue: this.state.area,
          pickerRowHeight:40,
          pickerTitleText: '选择地区',
          pickerCancelBtnText: '取消',
          pickerConfirmBtnText: '确定',
          onPickerConfirm: data => {
              let area_value = '';
              if(data[0] && data[1]){
                area_value = data[0] + ' ' + data[1]
              }
            this.setState({ area: data, area_value:area_value })
          }
        }
        Picker.init(payload)
        Picker.show()
    }

    //选择有效期
    handleShowValidDate = () => {
        let date = new Date();
        let year = date.getFullYear();

        let data = [
            ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
            []
        ]

        for(let i = 0; i < 30; i++){
            year = parseInt(year) + 1
            data[1].push(year.toString().substring(year.toString().length-2))
        }

        let payload = {
          pickerConfirmBtnColor: [55, 142, 251, 1],
          pickerCancelBtnColor: [55, 142, 251, 1],
          pickerBg: [255, 255, 255, 1],
          pickerData: data,
          pickerRowHeight:40,
          pickerTitleText: '选择有效期',
          pickerCancelBtnText: '取消',
          pickerConfirmBtnText: '确定',
          onPickerConfirm: data => {
            let str1 = data[0]
            let str2 = data[1]
            let str3 = `${str1 + '/' + str2}`
            this.setState({ valid_date: str3 })
          }
        }
        Picker.init(payload)
        Picker.show()
    }

    //选择账单日和还款日
    handleShowDays = (key) => () => {
        let payload = {
          pickerData: days,
          pickerConfirmBtnColor: [55, 142, 251, 1],
          pickerCancelBtnColor: [55, 142, 251, 1],
          pickerBg: [255, 255, 255, 1],
          selectedValue: this.state.key,
          pickerTitleText: '选择日期',
          pickerCancelBtnText: '取消',
          pickerConfirmBtnText: '确定',
          pickerRowHeight:40,
          onPickerConfirm: data => {
            let item = {}
            item[key] = data
            this.setState(item)
          }
        }
        Picker.init(payload)
        Picker.show()
      }
    render() {
        return (
            <View style={styles.container}>
                <ScrollView style={{ flex: 1 }} showsVerticalScrollIndicator={false}>
                    <View style={{ padding: 15, flexDirection: 'row', backgroundColor: "#ffffff", marginTop: 10, height: 50 }}>
                        <Text style={{ fontSize: 15, color: "#333333", alignSelf: 'center', width: 100 }}>真实姓名</Text>
                        <Text style={{ fontSize: 15, color: "#333333", alignSelf: 'center', width: 100 }}>{this.userInfo.user.real_name}</Text>
                    </View>
                    <View style={{ padding: 15, flexDirection: 'row', backgroundColor: "#ffffff", marginTop: 1, height: 50 }}>
                        <Text style={{ fontSize: 15, color: "#333333", alignSelf: 'center', width: 100 }}>身份证号</Text>
                        <Text style={{ fontSize: 15, color: "#333333", alignSelf: 'center' }}>{this.userInfo.user.idcard}</Text>
                    </View>
                    <View style={{ paddingHorizontal: 15, paddingVertical: 5, flexDirection: 'row', backgroundColor: "#ffffff", marginTop: 10 }}>
                        <Text style={{ fontSize: 15, color: "#333333", alignSelf: 'center', width: 100 }}>信用卡号</Text>
                        <TextInput style={{ fontSize: 15, color: '#333333', height: 40, flex: 1 }}
                            onChangeText={(text) => {
                                this.setState({ bank_card: text })
                            }}
                            keyboardType={'number-pad'}
                            placeholderTextColor={'#999999'}
                            underlineColorAndroid={'transparent'}
                            placeholder={'请输入信用卡号'}
                            value={this.state.bank_card}
                        />
                        <TouchableOpacity style={{ justifyContent: 'center' }} activeOpacity={0.8} onPress={() => {
                            this.showImagePicker()
                        }}>
                            <Image source={ImageRes.camer} style={{ width: 22, height: 22, alignSelf: 'center' }}></Image>
                        </TouchableOpacity>
                    </View>
                    <TouchableOpacity style={{ paddingHorizontal: 15, flexDirection: 'row', backgroundColor: "#ffffff", marginTop: 1, height: 50 }} activeOpacity={0.8} onPress={this.handleShowBankPicker}>
                        <Text style={{ fontSize: 15, color: "#333333", alignSelf: 'center', width: 100 }}>开户行</Text>
                        <Text style={{ flex: 1, fontSize: 15, color: this.state.bank_name ? "#333333" : "#999999", alignSelf: 'center', width: 100 }}>{this.state.bank_name ? this.state.bank_name : '请选择发卡行'}</Text>
                        <Image source={ImageRes.team_right_arrow} style={{ width: 10, height: 16, alignSelf: 'center', marginLeft: 10 }} />
                    </TouchableOpacity>
                    <TouchableOpacity style={{ paddingHorizontal: 15, flexDirection: 'row', backgroundColor: "#ffffff", marginTop: 1, height: 50 }} activeOpacity={0.8} onPress={this.handleShowPickerArea
                        // if (!this.state.bank_card) {
                        //     toast('请先填写银行卡号')
                        //     return
                        // }
                    }>
                        <Text style={{ fontSize: 15, color: "#333333", alignSelf: 'center', width: 100 }}>开户省市</Text>
                        <Text style={{ flex: 1, fontSize: 15, color: this.state.area_value ? "#333333" : "#999999", alignSelf: 'center', width: 100 }}>{this.state.area_value ? this.state.area_value : '请选择开户省市'}</Text>
                        <Image source={ImageRes.team_right_arrow} style={{ width: 10, height: 16, alignSelf: 'center', marginLeft: 10 }} />
                    </TouchableOpacity>
                    <TouchableOpacity style={{ paddingHorizontal: 15, flexDirection: 'row', backgroundColor: "#ffffff", marginTop: 1, height: 50 }} activeOpacity={0.8} onPress={this.handleShowValidDate}>
                        <Text style={{ fontSize: 15, color: "#333333", alignSelf: 'center', width: 100 }}>有效期</Text>
                        <Text style={{ flex: 1, fontSize: 15, color: this.state.valid_date ? "#333333" : "#999999", alignSelf: 'center', width: 100 }}>{this.state.valid_date ? this.state.valid_date : '请选择信用卡有效期'}</Text>
                        <Image source={ImageRes.team_right_arrow} style={{ width: 10, height: 16, alignSelf: 'center', marginLeft: 10 }} />
                    </TouchableOpacity>
                    <TouchableOpacity style={{ paddingHorizontal: 15, flexDirection: 'row', backgroundColor: "#ffffff", marginTop: 1, height: 50 }} activeOpacity={0.8} onPress={this.handleShowDays('statement_date')}>
                        <Text style={{ fontSize: 15, color: "#333333", alignSelf: 'center', width: 100 }}>账单日</Text>
                        <Text style={{ flex: 1, fontSize: 15, color: this.state.statement_date ? "#333333" : "#999999", alignSelf: 'center', width: 100 }}>{this.state.statement_date ? this.state.statement_date : '请选择信用卡账单日'}</Text>
                        <Image source={ImageRes.team_right_arrow} style={{ width: 10, height: 16, alignSelf: 'center', marginLeft: 10 }} />
                    </TouchableOpacity>
                    <TouchableOpacity style={{ paddingHorizontal: 15, flexDirection: 'row', backgroundColor: "#ffffff", marginTop: 1, height: 50 }} activeOpacity={0.8} onPress={this.handleShowDays('repayment_date')}>
                        <Text style={{ fontSize: 15, color: "#333333", alignSelf: 'center', width: 100 }}>还款日</Text>
                        <Text style={{ flex: 1, fontSize: 15, color: this.state.repayment_date ? "#333333" : "#999999", alignSelf: 'center', width: 100 }}>{this.state.repayment_date ? this.state.repayment_date : '请选择信用卡还款日'}</Text>
                        <Image source={ImageRes.team_right_arrow} style={{ width: 10, height: 16, alignSelf: 'center', marginLeft: 10 }} />
                    </TouchableOpacity>
                    <View style={{ paddingHorizontal: 15, paddingVertical: 5, flexDirection: 'row', backgroundColor: "#ffffff", marginTop: 1 }}>
                        <Text style={{ fontSize: 15, color: "#333333", alignSelf: 'center', width: 100 }}>安全码</Text>
                        <TextInput style={{ fontSize: 15, color: '#333333', height: 40, flex: 1 }}
                            onChangeText={(text) => {
                                this.setState({cvn2:text})
                            }}
                            keyboardType={'number-pad'}
                            placeholderTextColor={'#999999'}
                            underlineColorAndroid={'transparent'}
                            placeholder={'请输入信用卡背面后三位安全码'}
                            maxLength={11}
                            value={this.state.cvn2}
                        />
                    </View>
                    <View style={{ paddingHorizontal: 15, paddingVertical: 5, flexDirection: 'row', backgroundColor: "#ffffff", marginTop: 1 }}>
                        <Text style={{ fontSize: 15, color: "#333333", alignSelf: 'center', width: 100 }}>额度</Text>
                        <TextInput style={{ fontSize: 15, color: '#333333', height: 40, flex: 1 }}
                            onChangeText={(text) => {
                                this.setState({quota:text})
                            }}
                            keyboardType={'number-pad'}
                            placeholderTextColor={'#999999'}
                            underlineColorAndroid={'transparent'}
                            placeholder={'请输入信用卡额度'}
                            maxLength={11}
                            value={this.state.quota}
                        />
                    </View>
                    <View style={{ paddingHorizontal: 15, paddingVertical: 5, flexDirection: 'row', backgroundColor: "#ffffff", marginTop: 1 }}>
                        <Text style={{ fontSize: 15, color: "#333333", alignSelf: 'center', width: 100 }}>手机号码</Text>
                        <TextInput style={{ fontSize: 15, color: '#333333', height: 40, flex: 1 }}
                            onChangeText={(text) => {
                                this.setState({mobile:text})
                            }}
                            keyboardType={'number-pad'}
                            placeholderTextColor={'#999999'}
                            underlineColorAndroid={'transparent'}
                            placeholder={'请输入银行卡预留手机号码'}
                            maxLength={11}
                            value={this.state.mobile}
                        />
                    </View>
                    <TouchableOpacity style={{ marginTop: 50, backgroundColor: '#378EFB', justifyContent: 'center', marginHorizontal: 15, paddingVertical: 15, borderRadius: 5 }} activeOpacity={0.8} onPress={() => {
                        this.updateClick()
                    }}>
                        <Text style={{ fontSize: 15, color: "#ffffff", alignSelf: 'center' }}>修改</Text>
                    </TouchableOpacity>
                </ScrollView>
                <ProgressView show={this.state.loading} />
            </View >
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: Colors.bg_color
    }
});
function mapStateToProps(state) {
    return {
        userInfo: state.auth.userInfo
    }
}
const ExportView = connect(mapStateToProps)(BankCardInfoView);
module.exports.BankCardInfoView = ExportView
